function BattleController($scope, $timeout) {

    function EmptyBattleCell(location) {
        return new BattleCell('none', 'none', 0, location, 0);
    }

    function BattleCell(owner, type, hp, location, direction) {
        this.owner = owner;
        this.type = type;
        this.hp = hp;
        this.location = location;
        this.direction = direction;
        this.moved = false;
    }

    init = function() {
        $scope.battle_array = new Array();
        $scope.array_size = 10;
        for (var i = 0; i < $scope.array_size; i++) {
            $scope.battle_array[i] = EmptyBattleCell(i);
        }
        $scope.battle_array[0] = new BattleCell('P1', 'rock', 10, 0, 1);
        $scope.battle_array[1] = new BattleCell('P1', 'paper', 10, 0, 1);
        $scope.battle_array[$scope.array_size - 1] = new BattleCell('P2', 'scissors', 10, $scope.array_size - 1, -1);
        loop = function() {$timeout(loop, 2000);$scope.advance();}
        loop();
    }

    function MoveCell(arr, from, to) {
        arr[to] = arr[from];
        arr[from] = EmptyBattleCell();
        arr[to].location = to;
        arr[to].moved = true;
    }

    function UpdateArray(arr) {
        var needs_update = true;
        for (var i = 0; i < arr.length; ++i) {
            arr[i].moved = false;
        }
        while (needs_update) {
            needs_update = false;
            for (var i = 0; i < arr.length; ++i) {
                if (arr[i].type == 'none') {
                    var prev = arr[i-1];
                    var can_move_from_left = ((i > 0) && (prev.type != 'none') && (!prev.moved) && (prev.direction == 1));
                    var next = arr[i+1];
                    var can_move_from_right = ((i < (arr.length - 1)) && (next.type != 'none') && (!next.moved) && (next.direction == -1));
                    if (can_move_from_left && can_move_from_right) {
                        if (Math.random() > 0.5) {
                            can_move_from_left = false;
                        } else {
                            can_move_from_right = false;
                        }
                    }
                    if (can_move_from_left) {
                        MoveCell(arr, i - 1, i);
                        needs_update = true;
                    } else if (can_move_from_right) {
                        MoveCell(arr, i + 1, i);
                        needs_update = true;
                    }
                }
            }
        }
    }

    $scope.advance = function() {        
        UpdateArray($scope.battle_array);
    }

    init();
}
var AsciiWarModule = angular.module('AsciiWarModule', []);

AsciiWarModule.filter('cell_display', function() {
    return function(cell) {
        if (cell.type == 'none') return '.';
        else if (cell.type == 'scissors') return 'S';
        else if (cell.type == 'paper') return 'P';
        else if (cell.type == 'rock') return 'R';
        return 'E!';
    }
});